package com.rd.p2p.app.borrow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.BorrowAutoService;
import com.qdlc.p2p.biz.service.UserAutoTenderLogService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.tpp.TppBaseInterface;
import com.qdlc.p2p.biz.tpp.TppServiceFactory;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.checkrule.AutoTenderConfRuleCheck;
import com.qdlc.p2p.dal.common.RuleCheckHelper;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.BorrowAuto;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.BorrowAutoModel;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.util.UserUtils;

public class  AppBorrowAutoAction extends BaseAction<BorrowAutoModel> implements ModelDriven<BorrowAutoModel> {

    @Resource
    private BorrowAutoService borrowAutoService;

    @Resource
    private AccountService accountService;

    @Resource
    private UserIdentifyService userIdentifyService;

    @Resource
    private UserAutoTenderLogService userAutoTenderLogService;

    private User user;

    private Map<String, Object> data;

    /**
     * 我的自动投标设置
     * 
     * @return
     */
    @Action("/app/member/auto/detail")
    public void detail() throws Exception {
        user = getSessionUser();
        data = new HashMap<String, Object>();
        UserCache userCache = UserUtils.getUserCacheByUserId(user.getUserId());
        if (user == null || userCache== null || userCache.getUserType() == 2) {
            printWebResCodeAndMsgResult("-1","用户尚未登陆!");
            return;
        }
        Account account = accountService.findAccountByUserId(user.getUserId());
        BorrowAuto auto = borrowAutoService.init(user);
        data.put("auto", auto);
        data.put("account", account);
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i <= 12; i++) {
            list.add(i);
        }
        data.put("list", list);
        data.put("isImp", userCache.getIsImp());
        data.put("resCode", "1");
        data.put("resMsg", "请求成功");
        printWebJson(getStringOfJpaObj(data));
        return;
    }

    /**
     * 修改自动投标设置 如果是从关闭到开启，那么需要跳转到第三方处理业务
     * 
     * @return
     */
    @Action(value = "/app/member/auto/modify")
    public void modify() throws Exception {
        User u = getSessionUser();
        data = new HashMap<String, Object>();
        if (u == null) {
            printWebResCodeAndMsgResult("-1","用户尚未登陆!");
            return;
        }
        BorrowAuto a = borrowAutoService.findByUser(u);
        BorrowAuto auto = model.prototype();
        if (model.getAprDown() > 100) {
            printWebResCodeAndMsgResult("0", "投资最低利率过高");
            return;
        }
        auto.setAddTime(a.getAddTime());
        auto.setAddIp(a.getAddIp());
        auto.setUser(u);
        auto.setUpdateTime(a.getUpdateTime());
        if (!a.getEnable()) {
            // 开启自动投标需要先校验是否实名以及是否在双乾授权
            UserIdentify userIdentify = userIdentifyService.findByUserId(u.getUserId());
            if (userIdentify.getRealNameStatus() != 1 || StringUtil.isBlank(UserUtils.getUserTppCustId(userIdentify.getUserId()))) {
                printWebResCodeAndMsgResult("0","请先进行实名认证");
                return;
            }
            auto.setEnable(a.getEnable());
            borrowAutoService.update(auto);
            TppModel tppModel = new TppModel();
            tppModel.setUser(a.getUser());
            tppModel.setAutoTenderId(a.getId());
            TppBaseInterface tppService = TppServiceFactory.newIntance();
            Object autoTender = tppService.tppAutoTenderPlan(tppModel);
            data.put("autoTender", autoTender);
        } else {
            borrowAutoService.update(auto);
        }
        data.put("resCode", "1");
        data.put("resMsg", "修改投标设置成功");
        printWebJson(getStringOfJpaObj(data));
        return;
    }

    /**
     * 修改自动投标状态
     * 
     * @return
     */
    @Action("/app/member/auto/modifyStatus")
    public void modifyStatus() throws Exception {
        data = new HashMap<String, Object>();
        User u = getSessionUser();
        if(u==null){
            printWebResCodeAndMsgResult("-1","用户尚未登陆!");
            return;
        }
        if (model.getEnable()) {
            Account account = accountService.findAccountByUserId(getSessionUserId());
            AutoTenderConfRuleCheck autoTenderConf =  RuleCheckHelper.getValue(AutoTenderConfRuleCheck.class);
            // 开启自动投标不能小于最小可用余额
            double minUseMoney = autoTenderConf.auto_tender_min_usemoney;
            if (account.getUseMoney() < minUseMoney) {
                printWebResCodeAndMsgResult("0","账户可用余额最少为" + minUseMoney + "元才能体验自动投资");
                return;
            }
            printWebResCodeAndMsgResult("1","帐户可以开启");
            return;
        } else {
            BorrowAuto auto = borrowAutoService.findByUser(u);
            if (auto.getEnable()) {
                // -- 自动投标关闭
                TppModel tppModel = new TppModel();
                tppModel.setUser(u);
                tppModel.setAutoTenderId(auto.getId());
                TppBaseInterface tppService = TppServiceFactory.newIntance();
                boolean isClose = tppService.tppCloseAutoTenderPlan(tppModel);
                if (!isClose) {
                    printWebResCodeAndMsgResult("0","设置失败,请重试!");
                    return;
                }
            }
            printWebResCodeAndMsgResult("1","已关闭自动投标");
            return;
        }
    }

    @Action(value = "/app/member/auto/autoClose")
    public void autoClose() throws Exception {
        User u = getSessionUser();
        data = new HashMap<String, Object>();
        if (u == null) {
            printWebResCodeAndMsgResult("-1","用户尚未登陆!");
            return;
        }
        BorrowAuto auto = borrowAutoService.findByUser(u);
        if (auto == null) {
            printWebResCodeAndMsgResult("0","自动投标关闭失败！");
            return;
        }
        // -- 自动投标关闭
        TppModel tppModel = new TppModel();
        tppModel.setUser(u);
        tppModel.setAutoTenderId(auto.getId());
        TppBaseInterface tppService = TppServiceFactory.newIntance();
        Object tpClose = tppService.tppCloseAutoTenderPlan(tppModel);
        data.put("resCode", "1");
        data.put("resMsg", "自动关闭成功");
        data.put("autoTenderClose", tpClose);
        printWebJson(getStringOfJpaObj(data));
        return;
    }

}
